package com.fingard.dsp.bank.directbank.cwgs01;

import java.util.Calendar;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.bankInterface.ITransaction;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7515TodayTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7516HisTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.RetAtsTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.detail.RetAtsTransDetail;
import com.fingard.text.StringHelper;
import com.fingard.util.DateHelper;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

/**
 * Created by F on 2019/4/25.
 */
public class CWGS01Transaction extends CWGS01Base implements ITransaction {
    @Override
    public RetAtsTrans d_7516_HisTrans(Req7516HisTrans p_req7516) throws Exception {
        RetAtsTrans retAts = new RetAtsTrans(p_req7516.reqHeader);
        retAts.writeStart();
        CWGS01Header header = new CWGS01Header();
        header.batchNo = p_req7516.reqHeader.transSeqID;
        header.bizCode = "8372";
        Calendar tmpCalendarFrom = Calendar.getInstance();
        tmpCalendarFrom.setTime(p_req7516.getDateFrom());
        Calendar tmpCalendarTo = Calendar.getInstance();
        tmpCalendarTo.setTime(p_req7516.getDateTo());
        Calendar tmpCalendarStep =  Calendar.getInstance();
        String validCode = "";
        int tmpIntFrom = Integer.valueOf(Format.Date8Format.format(tmpCalendarFrom.getTime()));
        int tmpIntTo = Integer.valueOf(Format.Date8Format.format(tmpCalendarTo.getTime()));
        try {
            while (tmpIntFrom <= tmpIntTo) {
                if (DateHelper.compareMonth(tmpCalendarStep, tmpCalendarTo) == 0) {
                    tmpCalendarStep = tmpCalendarTo;
                } else {
                    tmpCalendarStep =  Calendar.getInstance();
                    tmpCalendarStep.set(Calendar.DAY_OF_MONTH, tmpCalendarStep.getActualMaximum(Calendar.DAY_OF_MONTH));
                }
                if (StringHelper.isNullOrEmpty(validCode)) {
                    validCode = login(p_req7516.reqHeader.transType);
                }
                XmlTextWriter xmlWriter = new XmlTextWriter();
                wirteCommenHeader(xmlWriter, header);
                xmlWriter.writeStartElement("BODY");
//                帐号总数	COUNT	N		帐号的总数，最多100条
                xmlWriter.writeElementString("COUNT", "1");
//                开始日期	START_DATE	D		YYYY-MM-DD
                xmlWriter.writeElementString("START_DATE", Format.Date10Format.format(tmpCalendarFrom.getTime()));
//                结束日期	END_DATE	D		YYYY-MM-DD
                xmlWriter.writeElementString("END_DATE", Format.Date10Format.format(tmpCalendarStep.getTime()));
//                用户名	USERNAME	C32		用户名
                xmlWriter.writeElementString("USERNAME", bankFront.loginName);
//                验证码	VALIDATE_CODE	C32		验证码
                xmlWriter.writeElementString("VALIDATE_CODE", validCode);
//                XML路径：XERP\BODY\DETAIL\ROW
                xmlWriter.writeStartElement("DETAIL");
                xmlWriter.writeStartElement("ROW");
//                账号	ACNT_NO	C32		财务公司内部账号
                xmlWriter.writeElementString("ACNT_NO", p_req7516.actNum);
                xmlWriter.writeEndDocument();
                String[] bankResult = sendToBank(xmlWriter.toXmlString());
                if (bankResult[0].length() == 0) {
                    StringBuilder tmpSbMsg = new StringBuilder();
                    XmlTextReader tmpBkReader = loadBankRespXmlReader(bankResult[1], tmpSbMsg);

                    String retCode = tmpBkReader.getFirstText("/XERP/BODY/RET_CODE");
                    String retMsg = tmpBkReader.getFirstText("/XERP/BODY/RET_MSG");
                    if ("0".equals(retCode)) {
                        while (tmpBkReader.read("/XERP/BODY/DETAIL/ROW/DETAIL/ROW")) {
                            RetAtsTransDetail transDetail = new RetAtsTransDetail();
//                            明细唯一标识	ROWTAG	C64
//                            本方账号	ACNT_NO	C32
                            transDetail.actNum = tmpBkReader.readedXElement.getSingleTextNotNull("ACNT_NO");
//                            凭证日期	VCH_DATE	D		YYYY-MM-DD
                            transDetail.tranTime = tmpBkReader.readedXElement.getSingleTextNotNull("BANK_DATE");
                            transDetail.tranDate = transDetail.tranTime.substring(0, 10);
                            transDetail.valueDate = tmpBkReader.readedXElement.getSingleTextNotNull("VCH_DATE");
//                              金额	AMOUNT	N
                            transDetail.tranAmt = tmpBkReader.readedXElement.getSingleTextNotNull("AMOUNT");
//                            方向	DIR	C2		1付款，2收款
                            String cdFlag = tmpBkReader.readedXElement.getSingleTextNotNull("DIR");
                            if (cdFlag.equals("1")) {
                                if (transDetail.tranAmt.indexOf("-") >= 0) {
                                    transDetail.cdFlag = "2";
                                    transDetail.tranAmt = transDetail.tranAmt.substring(1);
                                } else {
                                    transDetail.cdFlag = "1";
                                }
                            } else if (cdFlag.equals("2")) {
                                if (transDetail.tranAmt.indexOf("-") >= 0) {
                                    transDetail.cdFlag = "1";
                                    transDetail.tranAmt = transDetail.tranAmt.substring(1);
                                } else {
                                    transDetail.cdFlag = "2";
                                }
                            } else {
                                throw new Exception("借贷标志( " + cdFlag + ")无法识别，请与银行核对");
                            }
//                            余额	BALNCE	N		保留字段
                            transDetail.accBal = tmpBkReader.readedXElement.getSingleTextNotNull("BALNCE");
//                            凭证摘要	ABSTRACT	C1024	Y
                            transDetail.usage = tmpBkReader.readedXElement.getSingleTextNotNull("ABSTRACT");
                            transDetail.abstr = pickupAbstr(transDetail.usage);
//                            对方账号	OP_ACNT_NO	C32
                            transDetail.recAccNum = tmpBkReader.readedXElement.getSingleTextNotNull("OP_ACNT_NO");
//                            对方户名	OP_ACNT_NAME	C80
                            transDetail.recAccName = tmpBkReader.readedXElement.getSingleTextNotNull("OP_ACNT_NAME");
//                            交易流水号	TRANS_ID	C64	Y	业务单据唯一标识
                            transDetail.askNumber = tmpBkReader.readedXElement.getSingleTextNotNull("TRANS_ID");
                            retAts.writeRetDetail(transDetail);
                        }
                    } else {
                        throw new Exception(retCode + ":" + retMsg);
                    }
                } else {
                    throw new Exception(bankResult[1]);
                }
                tmpCalendarStep.add(Calendar.DAY_OF_MONTH, 1);
                tmpCalendarFrom = tmpCalendarStep;
                tmpIntFrom = Integer.valueOf(Format.Date8Format.format(tmpCalendarFrom.getTime()));
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            logout(validCode,p_req7516.reqHeader.transType);
        }
        if (retAts.getWrittenRdCount() == 0) {
            retAts.writeRespCode("0");
            retAts.writeRespInfo("交易为空");
        }
        retAts.writeEnd();
        return retAts;
    }

    @Override
    public RetAtsTrans d_7515_TodayTrans(Req7515TodayTrans p_req7515) throws Exception {
        RetAtsTrans retAts = new RetAtsTrans(p_req7515.reqHeader);
        retAts.writeStart();
        String validCode ="";
        try{
            validCode = login(p_req7515.reqHeader.transType);
            XmlTextWriter xmlWriter = new XmlTextWriter();
            CWGS01Header header =new CWGS01Header();
            header.batchNo = p_req7515.reqHeader.transSeqID;
            header.bizCode="8370";
            wirteCommenHeader(xmlWriter,header);
            xmlWriter.writeStartElement("BODY");
//            账号	ACNT_NO	C32	Y	财务公司内部账号
            xmlWriter.writeElementString("ACNT_NO", p_req7515.actNum);
//            用户名	USERNAME	C32		用户名
            xmlWriter.writeElementString("USERNAME", bankFront.loginName);
//            验证码	VALIDATE_CODE	C32		验证码
            xmlWriter.writeElementString("VALIDATE_CODE", validCode);
            xmlWriter.writeEndDocument();
            String[] bankResult = sendToBank(xmlWriter.toXmlString());
            if (bankResult[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(bankResult[1], tmpSbMsg);
                    String retCode = tmpBkReader.getFirstText("/XERP/BODY/RET_CODE");
                    String retMsg = tmpBkReader.getFirstText("/XERP/BODY/RET_MSG");
                    if ("0".equals(retCode)) {
                        while (tmpBkReader.read("/XERP/BODY/DETAIL/ROW")){
                            RetAtsTransDetail transDetail = new RetAtsTransDetail();
//                            明细唯一标识	ROWTAG	C64
//                            本方账号	ACNT_NO	C32
                            transDetail.actNum = tmpBkReader.readedXElement.getSingleTextNotNull("ACNT_NO");
//                            凭证日期	VCH_DATE	D		YYYY-MM-DD
                            transDetail.tranTime = tmpBkReader.readedXElement.getSingleTextNotNull("BANK_DATE");
                            transDetail.tranDate = transDetail.tranTime.substring(0,10);
                            transDetail.valueDate = tmpBkReader.readedXElement.getSingleTextNotNull("VCH_DATE");
//                              金额	AMOUNT	N
                            transDetail.tranAmt = tmpBkReader.readedXElement.getSingleTextNotNull("AMOUNT");
//                            方向	DIR	C2		1付款，2收款
                            String cdFlag = tmpBkReader.readedXElement.getSingleTextNotNull("DIR");
                            if (cdFlag.equals("1")) {
                                if(transDetail.tranAmt.indexOf("-")>=0) {
                                    transDetail.cdFlag = "2";
                                    transDetail.tranAmt = transDetail.tranAmt.substring(1);
                                }else{
                                    transDetail.cdFlag = "1";
                                }
                            } else if(cdFlag.equals("2")) {
                                if(transDetail.tranAmt.indexOf("-")>=0){
                                    transDetail.cdFlag = "1";
                                    transDetail.tranAmt = transDetail.tranAmt.substring(1);
                                }else{
                                    transDetail.cdFlag = "2";
                                }
                            }else {
                                throw new Exception("借贷标志( " + cdFlag + ")无法识别，请与银行核对");
                            }
//                            余额	BALNCE	N		保留字段
                            transDetail.accBal = tmpBkReader.readedXElement.getSingleTextNotNull("BALNCE");
//                            凭证摘要	ABSTRACT	C1024	Y
                            transDetail.usage =tmpBkReader.readedXElement.getSingleTextNotNull("ABSTRACT");
                            transDetail.abstr = pickupAbstr(transDetail.usage);
//                            对方账号	OP_ACNT_NO	C32
                            transDetail.recAccNum = tmpBkReader.readedXElement.getSingleTextNotNull("OP_ACNT_NO");
//                            对方户名	OP_ACNT_NAME	C80
                            transDetail.recAccName = tmpBkReader.readedXElement.getSingleTextNotNull("OP_ACNT_NAME");
//                            交易流水号	TRANS_ID	C64	Y	业务单据唯一标识
                            transDetail.askNumber = tmpBkReader.readedXElement.getSingleTextNotNull("TRANS_ID");
                            retAts.writeRetDetail(transDetail);
                        }
                    } else {
                        throw new Exception(retCode + ":" + retMsg);
                    }

            } else {
                throw new Exception(bankResult[1]);
            }
        }catch (Exception ex){
            ex.printStackTrace();
        }finally {
            logout(validCode,p_req7515.reqHeader.transType);
        }
        if (retAts.getWrittenRdCount() == 0) {
            retAts.writeRespCode("0");
            retAts.writeRespInfo("交易为空");
        }
        retAts.writeEnd();
        return retAts;

    }


}
